import React, { useState, useEffect } from 'react'
import { withRouter } from 'react-router-dom'
import PropTypes from 'prop-types'
import { routes as asyncRoutes, staticRoutes, initRoutes } from '@/router'
import RouterView from '@/router/routerView.js'
import eventBus from '@/util/eventBus'

let routesTable = []

function FrontendAuth(props) {
    const [currentRoutesTable, setCurrentRoutesTable] = useState([])
    const getRoutes = auth => {
        if (auth) {
            routesTable = [...staticRoutes, ...asyncRoutes]
        } else {
            routesTable = [...staticRoutes]
        }
        routesTable.push({
            path: "*",
            redirect: '/404',
            hidden: true
        })
        routesTable = initRoutes(routesTable)
        setCurrentRoutesTable(routesTable)
    }
    const auth = () => {
        if (window.sessionStorage.getItem('token')) {
            getRoutes(true)
        } else {
            getRoutes(false)
        }
    }
    useEffect(() => {
        auth()
    }, [])
    useEffect(() => {
        eventBus.on('updateRoutesTable', auth)
    }, [])
    useEffect(() => {
        if (!window.sessionStorage.getItem('token')) {
            props.history.push('/login/index')
        }
    }, [props.location.pathname])
    return <RouterView routesTable={ currentRoutesTable } {...props} />
}

FrontendAuth.propTypes = { 
	routesTable: PropTypes.array,
	location: PropTypes.object
}

export default withRouter(FrontendAuth)
export {
    routesTable
}